package com.dingding.dao.usermangerdao.impl;

import java.math.BigDecimal;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;

import org.hibernate.criterion.Criterion;
import org.hibernate.criterion.Restrictions;
import org.springframework.transaction.annotation.Propagation;
import org.springframework.transaction.annotation.Transactional;

import com.dingding.bean.databean.push.PushCompetitiveOrder;
import com.dingding.bean.databean.push.PushCurrentCity;
import com.dingding.bean.databean.request.ReqGetPushUerInfo;
import com.dingding.bean.databean.request.ReqResetAddress;
import com.dingding.bean.databean.request.ReqScanInfo;
import com.dingding.bean.databean.request.ReqUpdateUserInfo;
import com.dingding.bean.databean.request.ReqUserLoginByNum;
import com.dingding.bean.databean.request.ReqUserRegister;
import com.dingding.bean.databean.response.ResGetPushUserInfo;
import com.dingding.bean.databean.response.ResScanInfo;
import com.dingding.bean.databean.response.ResUserLoginByNum;
import com.dingding.bean.entity.Userdetail;
import com.dingding.common.core.beans.Userordert;
import com.dingding.common.core.im.IInstantMessenger;
import com.dingding.common.core.im.InstantMessengerFactory;
import com.dingding.common.core.im.dto.FormatType;
import com.dingding.common.core.util.DateFormatUtil;
import com.dingding.common.core.util.ToolUtil;
import com.dingding.dao.basedao.impl.BaseDaoImpl;
import com.dingding.dao.sql.UserOrderDaoSql;
import com.dingding.dao.sql.UserdetailServiceSQL;
import com.dingding.dao.usermangerdao.IUserDetailDao;

public class UserDetailDaoImpl extends BaseDaoImpl<Userdetail> implements IUserDetailDao {

	// 获取IM通信对象
	private IInstantMessenger instantMessenger = InstantMessengerFactory.createInstantMessengerPaltform();

	/**
	 * @Title: getResScanInfo @Description: 设置响应bean @param reqScanInfo
	 * 查看用户信息请求bean @param resScanInfo 查看用户信息响应bean @author Li
	 * Yi @return @throws
	 */
	public void getResScanInfo(ReqScanInfo reqScanInfo, ResScanInfo resScanInfo) {

		// 用于接收用户详情信息
		List<Object[]> list = null;
		try {
			// 得到用户详情信息
			list = super.sqlQueryListObj(UserdetailServiceSQL.GET_USER_DETAIL_INFO, false, reqScanInfo.getSideId());
		} catch (Exception e) {
			log.info("查看对方用户信息出现异常, 类：" + this.getClass() + "objectToResScanInfo()");
			return;
		}

		// 判断对方用户信息是否为空
		if (list != null && list.size() > 0) {
			this.objectToResScanInfo(reqScanInfo, resScanInfo, list.get(0));
		}

	}

	/**
	 * @Title: objectToResScanInfo @Description:
	 * 将Object[]转换为ResScanInfo实体bean @param obj 数据库查询到的数据 @param resScanInfo
	 * 查看用户信息响应bean @author Li Yi @return @throws
	 */
	public void objectToResScanInfo(ReqScanInfo reqScanInfo, ResScanInfo resScanInfo, Object[] obj) {

		// 用户昵称
		if (obj[0] != null) {
			resScanInfo.setNickName(obj[0].toString());
		}
		// 年龄
		if (obj[1] != null) {
			resScanInfo.setAge(ToolUtil.castInteger(obj[1]));
		}
		// 职业
		if (obj[2] != null) {
			resScanInfo.setOccupation(obj[2].toString());
		}
		// 籍贯
		if (obj[3] != null) {
			resScanInfo.setOrigin(obj[3].toString());
		}
		// 用户头像(地址)
		if (obj[4] != null) {
			resScanInfo.setUserAvatar(ToolUtil.imageAddress(obj[4].toString()));
		}
		// 用户头像缩略图
		if (obj[5] != null) {
			resScanInfo.setUserTabloidAvatar(ToolUtil.imageAddress(obj[5].toString()));
		}
		// 对方角色为车主
		if (reqScanInfo.getSideRole() == 1) {

			// 车牌号
			if (obj[6] != null) {
				resScanInfo.setLisencePlate(obj[6].toString());
			}
			// 车辆品牌
			if (obj[7] != null) {
				resScanInfo.setVehicleType(obj[7].toString());
			}
			// 车辆型号
			if (obj[8] != null) {
				resScanInfo.setVehicleModel(obj[8].toString());
			}
			// 车辆颜色
			if (obj[9] != null) {
				resScanInfo.setVehicleColor(obj[9].toString());
			}
			// 车辆图片
			if (obj[10] != null) {
				resScanInfo.setVehicleImage(ToolUtil.imageAddress(obj[10].toString()));
			}
		}
	}

	/**
	 * 
	 * @Title: getUserInfo @Description:用户抢单获取用户信息 @param userType 下单用户类型 @param
	 * userId 下单用户ID @param grabOrderUserId 抢单用户Id @author cheshaowei @throws
	 */
	@Override
	@Transactional(readOnly = true)
	public PushCompetitiveOrder getUserInfo(int userType, String userId, String grabOrderUserId) {

		String sql = null;
		// 乘客抢单,不需要获取车辆信息
		if (userType == 2) {
			sql = UserOrderDaoSql.PASSAGER_GRABORDER_GET_USER_INFO;
		} else {
			sql = UserOrderDaoSql.DRIVER_GRABORDER_GET_USER_INFO;
		}

		Object[] userDetalObj = super.sqlQueryUnResultObj(sql, false, grabOrderUserId, userId);

		PushCompetitiveOrder pushCompetitiveOrder = new PushCompetitiveOrder();

		// 数据转换
		converBean(userDetalObj, pushCompetitiveOrder);

		return pushCompetitiveOrder;
	}

	/**
	 * 
	 * @Title: converBean @Description:将查询到的数据转换成用户抢单推送bean @param userDetalObj
	 * 数据库中查询到的数据 @param pushCompetitiveOrder 推送数据封装bean @author
	 * cheshaowei @throws
	 */
	private void converBean(Object[] userDetalObj, PushCompetitiveOrder pushCompetitiveOrder) {
		// 下单用户ID
		if (userDetalObj[0] != null) {
			pushCompetitiveOrder.setPublishOrderUserId(userDetalObj[0].toString());
		}
		// 抢单用户头像
		if (userDetalObj[1] != null) {
			pushCompetitiveOrder.setUserAvatar(ToolUtil.imageAddress(userDetalObj[1].toString()));
		}
		// 昵称
		if (userDetalObj[2] != null) {
			pushCompetitiveOrder.setNickName(userDetalObj[2].toString());
		}
		// 手机号
		if (userDetalObj[3] != null) {
			pushCompetitiveOrder.setTellPhone(userDetalObj[3].toString());
		}
		// 设备类型
		if (userDetalObj[4] != null) {
			// 获取设备类型
			String equipmentType = userDetalObj[4].toString();

			if (equipmentType.equals("1")) { // 如果设备类型等于1，表示该设备类型为iOS
				pushCompetitiveOrder.setLoginEquipment("iOS");
			} else if (equipmentType.equals("2")) { // 如果设备类型等于2，表示该设备类型为Android
				pushCompetitiveOrder.setLoginEquipment("Android");
			}
		}
		// 下单人的手机号
		if (userDetalObj[5] != null) {
			pushCompetitiveOrder.setAnotherPhoneNo(userDetalObj[5].toString());
		}
		// 抢单人的头像缩略图
		if (userDetalObj[6] != null) {
			pushCompetitiveOrder.setUserTabloidAvatar(ToolUtil.imageAddress(userDetalObj[6].toString()));
		}
		// 抢单人的性别
		if (userDetalObj[7] != null) {
			pushCompetitiveOrder.setSex(ToolUtil.castInteger(userDetalObj[7]));
		}
		// 判断数组长度，来确定是否给pushCompetitiveOrder赋车辆信息
		if (userDetalObj.length > 8) {
			// 车辆品牌
			if (userDetalObj[8] != null) {
				pushCompetitiveOrder.setVehicleType(userDetalObj[8].toString());
			}
			// 车辆型号
			if (userDetalObj[9] != null) {
				pushCompetitiveOrder.setVehicleModel(userDetalObj[9].toString());
			}
			// 车辆颜色
			if (userDetalObj[10] != null) {
				pushCompetitiveOrder.setVehicleColor(userDetalObj[10].toString());
			}
			// 车辆照片
			if (userDetalObj[11] != null) {
				pushCompetitiveOrder.setVehicleImage(ToolUtil.imageAddress(userDetalObj[11].toString()));
			}
			// 车牌号
			if (userDetalObj[12] != null) {
				pushCompetitiveOrder.setLicensePlate(userDetalObj[12].toString());
			}
			// 司机姓名
			if (userDetalObj[13] != null) {
				pushCompetitiveOrder.setDriverName(userDetalObj[13].toString());
			}
			// 车主信誉度
			if (userDetalObj[14] != null) {
				pushCompetitiveOrder.setUserLevel(userDetalObj[14].toString());
			}
		}

	}

	/**
	 * @Title: saveUserDetail
	 * @Description: 保存到用户详情表
	 * @param reqUserRegister
	 *            -用户注册请求ben
	 * @param userLoginId
	 *            -登录id
	 * @param userDetailId
	 *            -详情表主键id
	 * @author Li Yi
	 * @return
	 */
	public void saveUserDetail(ReqUserRegister reqUserRegister, String userLoginId, String userDetailId) {

		Userdetail userdetail = new Userdetail();
		// 为用户详情表设置主键
		userdetail.setUdId(userDetailId);
		// 用户登录ID
		userdetail.setLoginId(userLoginId);
		// 用户昵称
		userdetail.setNickName(reqUserRegister.getNickName());
		// 用户性别
		userdetail.setSex(reqUserRegister.getSex());
		// 用户手机号码
		userdetail.setTellphone(reqUserRegister.getTelphone());
		// 注册时保存当前城市
		if (ToolUtil.isNotBlank(reqUserRegister.getLoginCity())) {
			userdetail.setCurrentCity(reqUserRegister.getLoginCity());
		}
		// 总搭乘
		userdetail.setTotalTake(new BigDecimal(0));
		// 总接程
		userdetail.setTotalWeldingProcess(new BigDecimal(0));
		// 总搭乘次数
		userdetail.setTotalTakeNumber(0);
		// 总接乘次数
		userdetail.setTotalWeldingProcessNumber(0);
		// 向用户详情表中插入一条记录
		super.save(userdetail);
	}

	/**
	 * 
	 * @Title: uploadUserAvatar @Description:设置用户头像 @param userId 用户ID @param
	 * url 图片访问路径 @author cheshaowei @throws
	 */
	@Override
	@Transactional(propagation = Propagation.REQUIRED)
	public void uploadUserAvatar(String userId, String url) {

		super.updateSqlRow(UserdetailServiceSQL.SET_USER_AVATAR, false, url, userId);

	}

	/**
	 * @Title: updateCurrentCity @Description: 更新用户的当前城市 @author
	 * lijinchao @return void @throws
	 */
	@Override
	public void updateCurrentCity(String currentCity, Userdetail userdetail) {

		// 设置当前城市
		userdetail.setCurrentCity(currentCity);
	}

	/**
	 * @Title: getUsers @Description: 转换可推送用户 @param object @author
	 * lijinchao @return PushCurrentCity @throws
	 */
	private PushCurrentCity getUsers(Object[] obj) {

		PushCurrentCity pushCurrentCity = new PushCurrentCity();

		// 用户id
		if (obj[0] != null) {
			pushCurrentCity.setId(obj[0].toString());
		}
		// 设备类型
		if (obj[1] != null) {
			pushCurrentCity.setDeviceType(obj[1].toString());
		}
		if (obj.length > 2) {
			// 上班时间
			if (obj[2] != null) {
				pushCurrentCity.setStartWorkTime((Date) obj[2]);
			}
			// 下班时间
			if (obj[3] != null) {
				pushCurrentCity.setEndWorkTime((Date) obj[3]);
			}
		}

		return pushCurrentCity;
	}

	/**
	 * @Title: getPushUserInfo @Description: 获取对方用户信息 @param
	 * reqGetPushUerInfo @author lijinchao @return Object @throws
	 */
	@Override
	public Object getPushUserInfo(ReqGetPushUerInfo reqGetPushUerInfo, Userordert userordert) {

		// 获取对方用户相关信息
		List<Object[]> objects = null;
		// 对方用户id
		String sideId = null;
		if (ToolUtil.isNotBlank(userordert.getPlaceOrderUserId())
				&& ToolUtil.isNotBlank(userordert.getGrabOrderUserId())) {
			// 如果该用户
			if (reqGetPushUerInfo.getUserId() == userordert.getPlaceOrderUserId()) {
				sideId = userordert.getGrabOrderUserId();
			} else {
				sideId = userordert.getPlaceOrderUserId();
			}
		}

		try {

			objects = sqlQueryListObj(UserdetailServiceSQL.GET_PUSH_USERINFO, false, sideId);
		} catch (Exception e) {
			// 异常
			log.error("抢单推送失败后，获取对方用户信息出现异常  类" + this.getClass() + " 方法：getPushUserInfo()", e);
			return 0;
		}

		// 判断对方用户细心是否存在
		if (objects == null || objects.size() <= 0) {
			// 用户不存在
			return 1;
		}

		return this.getPushUserInfoByObj(objects.get(0), sideId, userordert);
	}

	/**
	 * @Title: getPushUserInfoByObj @Description: 转换bean @param obj @author
	 * lijinchao @return ResGetPushUserInfo @throws
	 */
	private ResGetPushUserInfo getPushUserInfoByObj(Object[] obj, String sideId, Userordert userordert) {

		ResGetPushUserInfo resGetPushUserInfo = new ResGetPushUserInfo();
		// 对方用户id
		resGetPushUserInfo.setUserId(sideId);
		// 下单人id
		resGetPushUserInfo.setPublishOrderUserId(userordert.getPlaceOrderUserId());
		// 对方头像
		if (obj[0] != null) {
			resGetPushUserInfo.setUserAvatar(ToolUtil.imageAddress(obj[0].toString()));
		}
		// 对方昵称
		if (obj[1] != null) {
			resGetPushUserInfo.setUserName(obj[1].toString());
		}
		// 对方手机号
		if (obj[2] != null) {
			resGetPushUserInfo.setTellPhone(obj[2].toString());
		}
		// 车牌号
		if (obj[3] != null) {
			resGetPushUserInfo.setLisencePlate(obj[3].toString());
		}
		// 车辆品牌
		if (obj[4] != null) {
			resGetPushUserInfo.setVehicleType(obj[4].toString());
		}
		// 车辆型号
		if (obj[5] != null) {
			resGetPushUserInfo.setVehicleModel(obj[5].toString());
		}
		// 车辆颜色
		if (obj[6] != null) {
			resGetPushUserInfo.setVehicleColor(obj[6].toString());
		}
		// 车辆图片
		if (obj[7] != null) {
			resGetPushUserInfo.setVehicleImage(ToolUtil.imageAddress(obj[7].toString()));
		}
		// 对方头像缩略图
		if (obj[8] != null) {
			resGetPushUserInfo.setUserTabloidAvatar(ToolUtil.imageAddress(obj[8].toString()));
		}
		// 抢单时间
		resGetPushUserInfo.setGrabOrderTime(userordert.getGrabOrderTime());

		return resGetPushUserInfo;
	}

	/**
	 * @Title: updateUserInfo @Description: 更新用户资料 @param reqUpdateUserInfo
	 * 更新用户资料请求bean @param userdetail 用户详情对象 @author lijinchao @return
	 * void @throws
	 */
	@Override
	public void updateUserInfo(ReqUpdateUserInfo reqUpdateUserInfo, Userdetail userdetail) {

		// 昵称
		if (ToolUtil.isNotBlank(reqUpdateUserInfo.getNickName())) {
			userdetail.setNickName(reqUpdateUserInfo.getNickName());
		}
		// 年龄
		if (reqUpdateUserInfo.getAge() != null) {
			userdetail.setAge(reqUpdateUserInfo.getAge());
		}
		// 职业
		if (ToolUtil.isNotBlank(reqUpdateUserInfo.getOccupation())) {
			userdetail.setOccupation(reqUpdateUserInfo.getOccupation());
		}
		// 籍贯
		if (ToolUtil.isNotBlank(reqUpdateUserInfo.getOrigin())) {
			userdetail.setOrigin(reqUpdateUserInfo.getOrigin());
		}
		// 性别
		if (reqUpdateUserInfo.getSex() != null) {
			userdetail.setSex(reqUpdateUserInfo.getSex());
		}
	}

	/**
	 * @Title: getUserdetail @Description: 设置地址 @param reqResetAddress
	 * 设置地址-客户端请求bean @param userdetail 用户详情对象 @author lijinchao @throws
	 */
	@Override
	public void setUserdetailAddress(ReqResetAddress reqResetAddress, Userdetail userdetail) {

		// 家地址
		userdetail.setHomeAddress(reqResetAddress.getHomeAddress());
		// 家经度
		userdetail.setHomeLongitude(reqResetAddress.getHomeLongitude());
		// 家维度
		userdetail.setHomeLatitude(reqResetAddress.getHomeLatitude());
		// 公司地址
		userdetail.setCompanyAddress(reqResetAddress.getCompanyAddress());
		// 公司经度
		userdetail.setCompanyLongitude(reqResetAddress.getCompanyLongitude());
		// 公司纬度
		userdetail.setCompanyLatitude(reqResetAddress.getCompanyLatitude());
		// 上班时间
		userdetail.setStartworkTime(DateFormatUtil.HHmm(reqResetAddress.getStartWorkTime()));
		// 下班时间
		userdetail.setEndworkTime(DateFormatUtil.HHmm(reqResetAddress.getEndWorkTime()));
	}

	/**
	 * @Title: getPushUserList @Description: 根据订单信息获取推送用户信息 @param userordert
	 * 订单信息 @param startDistance 开始位置的范围 @param destinationDistance
	 * 目的地位置的范围 @author yuHaiQing @return List<PushCurrentCity> 返回类型 @throws
	 */
	@Override
	@Transactional(readOnly = true)
	public List<PushCurrentCity> getPushUserList(Userordert userordert, double startDistance,
			double destinationDistance) {

		// 创建用于存储推送用户对象
		List<PushCurrentCity> pushCurrentCities = new ArrayList<PushCurrentCity>();

		// 根据范围和订单ID获取推送用户列表
		List<Object[]> objects = sqlQueryListObj(UserdetailServiceSQL.GET_PUSH_USER_LIST, false, startDistance,
				destinationDistance, userordert.getOid());

		// 判断获取的用户列表是否为空
		if (objects == null || objects.size() <= 0) {
			return null;
		}

		// 遍历下单时要推送的用户列表，返回List<PushCurrentCity>集合
		for (Object[] objects2 : objects) {
			// 将PushCurrentCity对象添加到pushCurrentCities中
			pushCurrentCities.add(this.getUsers(objects2));
		}

		return pushCurrentCities;
	}

	/**
	 * @Title: saveUserDetailByNum
	 * @Description: 保存到用户详情表
	 * @param reqUserLoginByNum
	 *            -用户注册请求ben
	 * @param userLoginId
	 *            -登录id
	 * @param userDetailId
	 *            -详情表主键id
	 * @author Li Yi
	 * @return
	 */
	@Transactional(propagation = Propagation.REQUIRED)
	public void saveUserDetailByNum(ReqUserLoginByNum reqUserLoginByNum, String userLoginId, String userDetailId,
			ResUserLoginByNum resUserLoginByNum) {

		Userdetail userdetail = new Userdetail();
		// 为用户详情表设置主键
		userdetail.setUdId(userDetailId);
		// 用户登录ID
		userdetail.setLoginId(userLoginId);
		// 用户昵称
		userdetail.setNickName("叮叮小伙伴");
		// 用户性别
		userdetail.setSex(1);
		// 用户手机号码
		userdetail.setTellphone(reqUserLoginByNum.getUserName());
		// 用户头像设置
		userdetail.setUserAvatar("defaultAvatar.jpg");
		// 缩略图
		userdetail.setUserTabloidAvatar("thumbnail_defaultAvatar.jpg");
		// 总搭乘
		userdetail.setTotalTake(new BigDecimal(0));
		// 总接程
		userdetail.setTotalWeldingProcess(new BigDecimal(0));
		// 总搭乘次数
		userdetail.setTotalTakeNumber(0);
		// 总接乘次数
		userdetail.setTotalWeldingProcessNumber(0);
		// 新用户默认为5星
		userdetail.setUserLevel(new BigDecimal(5));

		// 添加用户当前城市
		if (ToolUtil.isNotBlank(reqUserLoginByNum.getCurrentCity())) {

			// 添加用户当前城市
			if (ToolUtil.isNotBlank(reqUserLoginByNum.getCurrentCity())) {
				userdetail.setCurrentCity(reqUserLoginByNum.getCurrentCity());
			}

		}
		
		// 获取token
		String token = this.getToken(userdetail);
		
		// 注册token
		userdetail.setToken(token);
		
		// 响应参数
		resUserLoginByNum.setToken(token);
		
		// 向用户详情表中插入一条记录
		super.save(userdetail);
	}

	/**
	 * @Title: updateCurrentCity
	 * @Description: 更新用户当前城市
	 * @param userId
	 *            用户id
	 * @param currentCity
	 *            当前城市
	 * @author fengshuonan
	 */
	public void updateCurrentCity(String userId, String currentCity) {

		if (ToolUtil.isBlank(userId) || ToolUtil.isBlank(currentCity)) {
			log.info("更新用户城市时候，用户id或者当前城市为空！");
			return;
		}

		Criterion criterion = Restrictions.eq("loginId", userId);

		// 声明用户详情对象
		Userdetail userdetail = null;

		try {
			userdetail = queryCriteriaUnResult(criterion, false);
		} catch (Exception e) {
			log.error("根据用户Id获取用户详情时出现异常  类：" + this.getClass() + " updateCurrentCity()", e);
		}

		if (userdetail != null) {

			// 给用户详情赋值（更新用户城市）
			userdetail.setCurrentCity(currentCity);

			if (ToolUtil.isBlank(userdetail.getToken())) {
				// 注册token
				userdetail.setToken(this.getToken(userdetail));
			}

		}

	}

	/**
	 * @Title: getToken
	 * @Description: 获取融云token，可连续获取三次，直到成功为止，如果第三次依然不成功，则返回null
	 * @param userdetail
	 *            用户详情对象
	 * @author YHQ
	 * @return String 返回类型
	 */
	public String getToken(Userdetail userdetail) {
		// 声明token对象
		String token = null;

		int i = 0;
		do {

			// 获取token信息
			token = instantMessenger.getToken(userdetail.getLoginId(), userdetail.getNickName(),
					ToolUtil.imageAddress(userdetail.getUserTabloidAvatar()), FormatType.json);

			// 判断获取token是否为空，如果为空则i+1,如果有值则i = -1
			if (token == null) {
				i++;
			}

		} while (token == null && i < 3);

		return token;
	}

	/**
	 * @Title: getUserDetailInfo
	 * @Description: 根据用户Id获取用户详情信息
	 * @param userId
	 *            用户Id
	 * @author YHQ
	 * @return void 返回类型
	 */
	@Override
	public Userdetail getUserDetailInfo(String userId) {

		// 添加查询条件
		Criterion criterion = Restrictions.eq("loginId", userId);

		try {
			return super.queryCriteriaUnResult(criterion, false);
		} catch (Exception e) {
			log.error("根据用户Id获取用户详情信息时出现异常 类：" + this.getClass() + " getUserDetailInfo()", e);
		}

		return null;
	}

	/**
	 * 
	 * 乘客评价完成后，重新计算车主信誉等级并更新
	 * 
	 * @Title: updateUserReputateLevel 
	 * @param driverId 车主ID 
	 * @return  boolean true 成功 false 失败
	 * @author CHEHAUNBO
	 * 
	 */
	@Override
	@Transactional(propagation = Propagation.REQUIRED)
	public boolean updateUserReputateLevel(String driverId) {

		try {
			int row = super.updateSqlRow(UserdetailServiceSQL.UPDATE_REPUTE_LEVEL, driverId,driverId,driverId);
			if (row > 0) {
				return true;
			}
		} catch (Exception e) {
			log.error("乘客评价完成后，重新计算车主信誉等级并更新出现异常！", e);
		}

		return false;
	}

}
